package cn.lxb.netstat.collector;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.validation.constraints.NotNull;

import lombok.extern.slf4j.Slf4j;

/**
 * @author TFB
 */
@Slf4j
public class MemoryAddressRepository implements AddressRepository {

	protected Map<String, Set<String>> appToAddress = new ConcurrentHashMap<>();
	protected AtomicBoolean changed = new AtomicBoolean(false);

	@Override
	public void save(RecordParam recordParam) {
		Set<String> addresses = appToAddress.get(recordParam.serviceName);
		boolean b = false;
		if (addresses == null) {
			synchronized (appToAddress) {
				// double check
				addresses = appToAddress.get(recordParam.serviceName);
				if (addresses == null) {
					addresses = new CopyOnWriteArraySet<>();
					addresses.add(recordParam.getAddress());
					appToAddress.put(recordParam.serviceName, addresses);
					b = true;
				}
			}
		} else if (!addresses.contains(recordParam.address)) {
			addresses.add(recordParam.getAddress());
			b = true;
		}

		if (b) {
			changed.compareAndSet(false, true);
			log.debug("加入了新的地址:{}-----{}", recordParam.serviceName, recordParam.address);
		}
	}
	

	@Override
	public void remove(@NotNull RecordParam recordParam) {
		Set<String> addresses = appToAddress.get(recordParam.serviceName);
		if (addresses != null && addresses.remove(recordParam.getAddress())) {
			changed.compareAndSet(false, true);
		}
	}

	@Override
	public Set<String> queryByAppName(String serviceName) {
		return appToAddress.get(serviceName);
	}

	@Override
	public Map<String, Set<String>> queryAll() {
		return appToAddress;
	}

	@Override
	public void clear() {
		appToAddress.clear();
		log.warn("已清空内存中的数据!!");
		changed.compareAndSet(false, true);
	}

}
